package repository.relsys.services.datacentral;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.log4j.Logger;

import repository.relsys.app.*;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;

public class FileDataProvider implements DataProvider {

	private String fileName;
	private String syntax;
	private Logger logger = Logger.getLogger(this.getClass().getName());
	Model dataModel = null;

	// public FileDataProvider(){}
	/*
	 * public FileDataProvider(String dataSourceUrl, String syntax) { super();
	 * this.fileName = dataSourceUrl; this.syntax = syntax; }
	 */

	@Override
	public Model getData() {

		try {

			fileName = Settings.getInstance().config.jenaConfig.fileDataProviderUrl;
			syntax = Settings.getInstance().config.jenaConfig.defaultRDFSyntax;

			dataModel = ModelFactory.createDefaultModel();
			dataModel.setNsPrefix("lt",
					"http://diplomski.nelakolundzija.org/LTontology.rdf#");
			dataModel.setNsPrefix("swc",
					"http://data.semanticweb.org/ns/swc/ontology#");
			dataModel.setNsPrefix("jenabean", "http://thewebsemantic.com/");
			dataModel.setNsPrefix("dc", "http://purl.org/dc/elements/1.1/");
			dataModel.setNsPrefix("xsd", "http://www.w3.org/2001/XMLSchema#");
			dataModel.setNsPrefix("rdfs",
					"http://www.w3.org/2000/01/rdf-schema#");

			dataModel.read(new FileInputStream(fileName),
					"http://diplomski.nelakolundzija.org/LTontology.rdf#",
					syntax);
		} catch (Exception e) {
			logger
					.error(
							"Could not load DataModel from file: "
									+ Settings.getInstance().config.jenaConfig.fileDataProviderUrl,
							e);
		}

		return dataModel;

	}

	@Override
	public void updateDataSource(Model m) {
		try {

			fileName = Settings.getInstance().config.jenaConfig.fileDataProviderUrl;
			syntax = Settings.getInstance().config.jenaConfig.defaultRDFSyntax;

			dataModel.write(new FileOutputStream(fileName), syntax,
					"http://diplomski.nelakolundzija.org/LTontology.rdf#");

		} catch (Exception e) {
			logger.error("Couldn't flush dataModel to repository", e);
		}

	}
}
